package aiku.numericalcontroloa.Service.DepartmentManagement.Impl;

import aiku.numericalcontroloa.Base.Utils.HttpStatus;
import aiku.numericalcontroloa.Base.Utils.Result;
import aiku.numericalcontroloa.Mapper.DepartmentManagement.DepartmentMapper;
import aiku.numericalcontroloa.Mapper.DepartmentManagement.EmployeeDepartmentMapper;
import aiku.numericalcontroloa.Model.Dto.DepartmentManagement.DepartmentDto;
import aiku.numericalcontroloa.Model.Entity.BaseEntity;
import aiku.numericalcontroloa.Model.Entity.DepartmentManagement.Department;
import aiku.numericalcontroloa.Model.Entity.DepartmentManagement.DepartmentWithUser;
import aiku.numericalcontroloa.Model.Entity.DepartmentManagement.EmployeeDepartment;
import aiku.numericalcontroloa.Model.Vo.DepartmentManagement.DepartmentVo;
import aiku.numericalcontroloa.Service.DepartmentManagement.DepartmentService;
import aiku.numericalcontroloa.project.system.mapper.SysRoleMapper;
import aiku.numericalcontroloa.project.system.pojo.entity.SysRole;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author 黄广庭
 * @Date 2024/2/20 9:38
 */
@Service
public class DepartmentServiceImpl implements DepartmentService {
    private final DepartmentMapper departmentMapper;
    private final EmployeeDepartmentMapper employeeDepartmentMapper;
    private final SysRoleMapper sysRoleMapper;

    public DepartmentServiceImpl(DepartmentMapper departmentMapper, EmployeeDepartmentMapper employeeDepartmentMapper, SysRoleMapper sysRoleMapper) {
        this.departmentMapper = departmentMapper;
        this.employeeDepartmentMapper = employeeDepartmentMapper;
        this.sysRoleMapper = sysRoleMapper;
    }

    @Override
    @Transactional
    public Result addDepartment(DepartmentDto departmentDto) {
        if (departmentDto == null){
            return new Result(HttpStatus.BAD_REQUEST,"参数不能为空");
        }
        // 添加部门
        Department department = new Department();
        department.setName(departmentDto.getName());
        department.setParentDepartmentId(departmentDto.getParentDepartmentId());
        department.setManagerId(departmentDto.getManagerId());
        departmentMapper.insert(department);
        // 将主管添加到员工部门表
        EmployeeDepartment employeeDepartment = new EmployeeDepartment();
        employeeDepartment.setEmployeeId(departmentDto.getManagerId());
        employeeDepartment.setDepartmentId(department.getId());
        employeeDepartmentMapper.insert(employeeDepartment);
        return Result.success("添加成功");
    }

    @Override
    @Transactional
    public Result deleteDepartment(DepartmentDto departmentDto) {
        if (departmentDto == null || departmentDto.getId() == null){
            return new Result(HttpStatus.BAD_REQUEST,"参数不能为空");
        }

        Department department = departmentMapper.selectById(departmentDto.getId());

        if (department == null){
            return new Result(HttpStatus.BAD_REQUEST,"参数错误");
        }
        // 删除该部门以及下级部门
        recursionDelete(department);
        return Result.success("删除成功");
    }

    @Override
    @Transactional
    public Result updateDepartment(DepartmentDto departmentDto) {
        Department department = departmentMapper.selectById(departmentDto.getId());
        if (department == null){
            return new Result(HttpStatus.BAD_REQUEST,"参数错误");
        }
        LambdaUpdateWrapper<Department> departmentLUW = new LambdaUpdateWrapper<>();
        departmentLUW.eq(Department::getId,departmentDto.getId())
                .set(Department::getName,departmentDto.getName())
                .set(Department::getManagerId,departmentDto.getManagerId())
                .set(Department::getParentDepartmentId,departmentDto.getParentDepartmentId());
        departmentMapper.update(null, departmentLUW);
        // 把员工部门表中的主管移除，添加新的主管
        LambdaQueryWrapper<EmployeeDepartment> employeeDepartmentLQW = new LambdaQueryWrapper<>();
        employeeDepartmentLQW.eq(EmployeeDepartment::getDepartmentId,department.getId())
                .eq(EmployeeDepartment::getEmployeeId,department.getManagerId());
        employeeDepartmentMapper.delete(employeeDepartmentLQW);
        EmployeeDepartment employeeDepartment = new EmployeeDepartment();
        employeeDepartment.setEmployeeId(departmentDto.getManagerId());
        employeeDepartment.setDepartmentId(department.getId());
        employeeDepartmentMapper.insert(employeeDepartment);
        return Result.success("修改成功");
    }

    @Override
    public Result getDepartmentList() {
        List<DepartmentVo> departmentVoList = new ArrayList<>();
        List<DepartmentWithUser> departmentWithUserList = departmentMapper.selectDepartmentWithUserList(null);
        // 筛选顶级部门，上级部门字段为空为顶级部门
        for (DepartmentWithUser departmentWithUser : departmentWithUserList){
            if (departmentWithUser.getParentDepartmentId() == null
                    || departmentWithUser.getParentDepartmentId().isEmpty()){
                DepartmentVo departmentVo = new DepartmentVo();
                BeanUtils.copyProperties(departmentWithUser,departmentVo);
                SysRole sysRole = sysRoleMapper.selectById(departmentWithUser.getRoleId());
                String managerName = departmentWithUser.getNickName()+"("+sysRole.getNameZh()+")";
                departmentVo.setManagerName(managerName);
                departmentVoList.add(departmentVo);
            }
        }
        //System.out.println("顶级部门列表==>"+departmentVoList);
        if (departmentVoList.size() > 0){
            // 再根据顶级部门id，遍历对比上级部门字段查找下级部门
            for (DepartmentVo departmentVo : departmentVoList){
                departmentVo.setChildren(getChildrenList(departmentVo,departmentWithUserList));
            }
        }
        return Result.success("查询成功",departmentVoList);
    }

    @Override
    public Result getDepartment(DepartmentDto departmentDto) {
        if (departmentDto == null || departmentDto.getId() == null){
            return new Result(HttpStatus.BAD_REQUEST,"缺少参数");
        }
        DepartmentWithUser departmentWithUser = departmentMapper.selectDepartmentWithUser(departmentDto.getId());
        if (departmentWithUser == null){
            return new Result(HttpStatus.BAD_REQUEST,"参数错误");
        }
        DepartmentVo departmentVo = new DepartmentVo();
        BeanUtils.copyProperties(departmentWithUser,departmentVo);
        departmentVo.setManagerName(departmentWithUser.getNickName());
        return Result.success("查询成功",departmentVo);
    }

    @Override
    public Result selectDepartments() {
        List<Department> departmentList = departmentMapper.selectList(null);
        return Result.success("查询成功",departmentList);
    }

    protected List<DepartmentVo> getChildrenList(DepartmentVo departmentVo,List<DepartmentWithUser> departmentWithUserList) {
        List<DepartmentVo> childrenList = new ArrayList<>();
        // 遍历判断item的parentDepartmentId是否等于departmentVo的id
        // 等于则说明item是departmentVo的下级部门
        for (DepartmentWithUser item : departmentWithUserList) {
            if (departmentVo.getId().equals(item.getParentDepartmentId())) {
                DepartmentVo children = new DepartmentVo();
                BeanUtils.copyProperties(item, children);
                SysRole sysRole = sysRoleMapper.selectById(item.getRoleId());
                String managerName = item.getNickName()+"("+sysRole.getNameZh()+")";
                children.setManagerName(managerName);
                childrenList.add(children);
            }
        }
        // 没有下级部门则结束方法
        if (childrenList.size() == 0){
            return childrenList;
        }
        // 递归查找下级部门的下级部门
        for (DepartmentVo item : childrenList){
            item.setChildren(getChildrenList(item,departmentWithUserList));
        }
        return childrenList;
    }

    @Transactional
    protected void recursionDelete(Department department){
        // 删除该部门
        departmentMapper.deleteById(department.getId());
        // 删除该部门的员工部门表记录
        LambdaQueryWrapper<EmployeeDepartment> employeeDepartmentLQW = new LambdaQueryWrapper<>();
        employeeDepartmentLQW.eq(EmployeeDepartment::getDepartmentId,department.getId());
        employeeDepartmentMapper.delete(employeeDepartmentLQW);

        // 根据部门表的上级部门字段，查询该部门的下级部门
        LambdaQueryWrapper<Department> departmentLQW = new LambdaQueryWrapper<>();
        departmentLQW.eq(Department::getParentDepartmentId,department.getId());
        List<Department> departmentList = departmentMapper.selectList(departmentLQW);
        // 大小为0，没有下级部门，结束方法
        if (departmentList.size() == 0){
            return;
        }
        // 不为0，遍历递归
        for (Department item : departmentList){
            recursionDelete(item);
        }
    }
}
